package edu.hitwh.service;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.hitwh.entity.Book;
import edu.hitwh.repository.BookQuery;
import edu.hitwh.repository.BookRepository;
import edu.hitwh.repository.BookSpecification;
import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class BookService {
    private final BookRepository bookRepository;

    public Page<Book> searchBooks(BookQuery query, Pageable pageable) {
        return bookRepository.findAll(BookSpecification.getSpecification(query), pageable);
    }

    @Transactional
    public void addCopies(Long id, Integer copies) {
        if(copies <= 0) {
            throw new RuntimeException("Copies must be positive");
        }
        Book book = bookRepository.findById(id).orElseThrow(() -> new RuntimeException("Book not found"));
        if(book.getRemoved()) {
            throw new RuntimeException("Book removed");
        }
        book.setTotalCopies(book.getTotalCopies() + copies);
        book.setAvailableCopies(book.getAvailableCopies() + copies);
    }

    @Transactional
    public void removeCopies(Long id, Integer copies) {
        if(copies <= 0) {
            throw new RuntimeException("Copies must be positive");
        }
        Book book = bookRepository.findById(id).orElseThrow(() -> new RuntimeException("Book not found"));
        if(book.getAvailableCopies() < copies) {
            throw new RuntimeException("Not enough copies");
        }
        book.setTotalCopies(book.getTotalCopies() - copies);
        book.setAvailableCopies(book.getAvailableCopies() - copies);
    }

    public void createBook(Book book) {
        book.setRemoved(false);
        bookRepository.save(book);
    }

    
    public void removeBook(Integer id) {
        // search if total copies is 0
        Book book = bookRepository.findById((long) id).orElseThrow(() -> new RuntimeException("Book not found"));
        if(book.getTotalCopies() != 0) {
            throw new RuntimeException("Book has copies");
        }
        book.setRemoved(true);
        bookRepository.save(book);
    }
}